<template>
  <div class="min-h-screen bg-gradient-to-b from-gray-50 to-white">
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <a-tabs
        v-model:activeKey="activeTab"
        class="mb-6"
        @change="handleTabChange"
        :animated="false"
      >
        <!-- 待审批 -->
        <a-tab-pane key="pending" tab="待审批">
          <template v-if="activeTab === 'pending'">
            <div class="overflow-auto">
              <a-table
                :dataSource="pendingTools"
                :columns="pendingColumns"
                :pagination="pagination"
                @change="handleTableChange"
                :scroll="{ x: 1500, y: 600 }"
                :loading="isLoading"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'type' || column.key === 'tag'">
                    <span
                      :class="getTagStyle(column.key === 'type' ? record.type : record.tag, column.key)"
                      :title="column.key === 'type' ? record.type : record.tag"
                    >
                      {{ column.key === 'type' ? record.type : record.tag }}
                    </span>
                  </template>
                  <template v-if="column.key === 'action'">
                    <div class="flex gap-2">
                      <a-button type="primary" size="small" @click="handleApprove(record)">通过</a-button>
                      <a-button danger size="small" @click="handleReject(record)">拒绝</a-button>
                    </div>
                  </template>
                </template>
              </a-table>
            </div>
          </template>
        </a-tab-pane>

        <!-- 已审批 -->
        <a-tab-pane key="approved" tab="已审批">
          <template v-if="activeTab === 'approved'">
            <div class="overflow-auto">
              <a-table
                :dataSource="approvedTools"
                :columns="approvedColumns"
                :pagination="pagination"
                @change="handleTableChange"
                :scroll="{ x: 1800, y: 600 }"
                :loading="isLoading"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'type' || column.key === 'tag'">
                    <span
                      :class="getTagStyle(column.key === 'type' ? record.type : record.tag, column.key)"
                      :title="column.key === 'type' ? record.type : record.tag"
                    >
                      {{ column.key === 'type' ? record.type : record.tag }}
                    </span>
                  </template>
                  <template v-if="column.key === 'status'">
                    <span :class="getTagStyle(record.status, 'status')">{{ record.status }}</span>
                  </template>
                  <template v-if="column.key === 'action'">
                    <div class="flex gap-2">
                      <a-button
                        :type="record.status === '已上架' ? 'default' : 'primary'"
                        size="small"
                        @click="handleToggleStatus(record)"
                      >
                        {{ record.status === '已上架' ? '下架' : '上架' }}
                      </a-button>
                      <a-popconfirm
                        title="确定要删除这个工具吗？"
                        @confirm="handleDelete(record)"
                        okText="确定"
                        cancelText="取消"
                      >
                        <a-button danger size="small">删除</a-button>
                      </a-popconfirm>
                    </div>
                  </template>
                </template>
              </a-table>
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, h, onMounted, nextTick, computed } from 'vue'
import type { TableProps } from 'ant-design-vue'
import { getReviewPage, reviewTool, updateToolStatus, deleteTool,publishTool,unpublishTool } from '@/utils/api'
import { message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import $loading from '@/utils/loading';

// === 状态 & 数据 ===
const activeTab = ref('pending')
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 20,
  showSizeChanger: true,
  showQuickJumper: true
})
const pendingTools = ref<any[]>([])
const approvedTools = ref<any[]>([])
const isLoading = ref(false)

// === 列配置 ===
const pendingColumns = computed(() => [
  { title: '工具名称', dataIndex: 'name', key: 'name', width: 150, fixed: 'left', ellipsis: true },
  { title: '链接地址', dataIndex: 'link', key: 'link', width: 200, ellipsis: true,
    customRender: ({ text }) => h('a', { href: text, target: '_blank' }, text)
  },
  { title: '功能介绍', dataIndex: 'description', key: 'description', width: 250, ellipsis: true },
  { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
  { title: '标签', dataIndex: 'tag', key: 'tag', width: 100 },
  { title: '提交人', dataIndex: 'submitter', key: 'submitter', width: 120 },
  { title: '提交时间', dataIndex: 'submitTime', key: 'submitTime', width: 160 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
])

const approvedColumns = computed(() => [
  { title: '工具名称', dataIndex: 'name', key: 'name', width: 150, fixed: 'left', ellipsis: true },
  { title: '链接地址', dataIndex: 'link', key: 'link', width: 200, ellipsis: true,
    customRender: ({ text }) => h('a', { href: text, target: '_blank' }, text)
  },
  { title: '功能介绍', dataIndex: 'description', key: 'description', width: 250, ellipsis: true },
  { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
  { title: '标签', dataIndex: 'tag', key: 'tag', width: 100 },
  { title: '提交人', dataIndex: 'submitter', key: 'submitter', width: 120 },
  { title: '提交时间', dataIndex: 'submitTime', key: 'submitTime', width: 160 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '审批时间', dataIndex: 'approveTime', key: 'approveTime', width: 160 },
  { title: '审核状态', dataIndex: 'approveStatus', key: 'approveStatus', width: 100,
    customRender: ({ text }) => h('span', { class: getTagStyle(text, 'approveStatus') }, text)
  },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
])

// === 样式映射 ===
const typeStyles = {
  '测试工具': 'bg-blue-50 text-blue-600',
  'AI模型': 'bg-green-50 text-green-600',
  'AI应用': 'bg-orange-50 text-orange-600'
}
const tagStyles = {
  '自动化测试': 'bg-purple-50 text-purple-600',
  'AI造数': 'bg-pink-50 text-pink-600',
  '性能测试': 'bg-indigo-50 text-indigo-600',
  '接口测试': 'bg-cyan-50 text-cyan-600'
}
const statusStyles = {
  '已上架': 'bg-green-50 text-green-600',
  '已下架': 'bg-gray-50 text-gray-600',
  '已通过': 'bg-green-50 text-green-600',
  '已拒绝': 'bg-red-50 text-red-600'
}
const getTagStyle = (value: string, category: 'type' | 'tag' | 'status' | 'approveStatus') => {
  const base = 'px-2 py-1 rounded-full text-sm whitespace-nowrap'
  const map = { type: typeStyles, tag: tagStyles, status: statusStyles, approveStatus: statusStyles }
  return `${base} ${map[category][value] || ''}`
}

// === 核心数据加载 ===
const safeRender = async (force = false) => {
  const loadingInstance = $loading.show();
  try {
    await nextTick()
    const params: any = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...(activeTab.value === 'pending'
        ? { approvalStatus: 0 }
        : { approvalStatusList: [1, 2] })
    }
    const res = await getReviewPage(params)
    if (res) {
      const { records, total } = res
      const mapped = records.map(item => ({
        id: item.reviewId,
        relatedId: item.relatedId,
        name: item.tool.toolName,
        link: item.tool.linkAddress,
        description: item.tool.functionDescription,
        type: item.tool.category,
        tag: item.tool.tags,
        submitter: item.tool.creators,
        submitTime: new Date(item.submissionTime).toLocaleString(),
        status: item.tool.isPublished == 1 ? '已上架' : '已下架',
        approveTime: item.approvalTime ? new Date(item.approvalTime).toLocaleString() : '-',
        approveStatus: item.approvalStatus === '1' ? '已通过' : '已拒绝'
      }))
      if (activeTab.value === 'pending') {
        pendingTools.value = mapped
      } else {
        approvedTools.value = mapped
      }
      pagination.value.total = total
    }
  } catch (e) {
    console.error('获取审核列表失败:', e)
    message.error('获取审核列表失败')
  } finally {
    loadingInstance.close();
  }
}
const debouncedSafeRender = debounce(safeRender, 700)

// 事件处理
const handleTableChange: TableProps['onChange'] = (page) => {
  pagination.value.current = page.current || 1
  pagination.value.pageSize = page.pageSize || 20
  debouncedSafeRender()
}
const handleTabChange = () => {
  pagination.value.current = 1
  if (activeTab.value === 'pending') pendingTools.value = []
  else approvedTools.value = []
  debouncedSafeRender(true)
}
const handleApprove = async (rec: any) => {
  try {
    await reviewTool({ relatedId: rec.relatedId, approvalStatus: 1 })
    message.success('审批通过成功')
    debouncedSafeRender(true)
  } catch {
    message.error('审批失败')
  }
}
const handleReject = async (rec: any) => {
  try {
    await reviewTool({ relatedId: rec.relatedId, approvalStatus: 2 })
    message.success('审批拒绝成功')
    debouncedSafeRender(true)
  } catch {
    message.error('审批失败')
  }
}
const handleToggleStatus = async (rec: any) => {
  let result;
  try {
    if (rec.status === '已上架') {
      result =  await unpublishTool(rec.relatedId)
      message.success('下架成功')
    } else {
      result =  await publishTool(rec.relatedId)
      message.success('上架成功')
    }
    debouncedSafeRender(true)
  } catch {
    message.error(result?.data || '没有权限操作')
  }
}
const handleDelete = async (rec: any) => {
  try {
    await deleteTool({ toolId: rec.relatedId })
    message.success('删除成功')
    debouncedSafeRender(true)
  } catch {
    message.error('删除工具失败')
  }
}

// 首次加载
onMounted(() => {
  debouncedSafeRender()
})
</script>

<style scoped>
/* 如果需要，可在这里固定外层容器高度 */
.overflow-auto {
  max-height: 600px;
}
</style>
